<template>
    <div>
      
      <el-card class="qianming-container" body-style="padding:0px">
        <vue-esign
          ref="esign"
          :isCrop="isCrop"
          :width="600"
          :height="300"
          :lineWidth="lineWidth"
          :lineColor="lineColor"
          :format="'image/png'"
          :bgColor.sync="bgColor"
        ></vue-esign>
        <div class="contro-container">
          <el-button type="danger" @click="handleReset">清空画板</el-button>
          <el-button type="primary" @click="handleGenerate">确认签名</el-button>
        </div>
      </el-card>
    </div>
  </template>
    
  <script>
  import vueEsign from "vue-esign";
  import {uploadPhoto} from "@/api/city"
  export default {
    props: {
        fileName: {
      type: String,
      default: 'sign'
    }
  },
    components: { vueEsign },
    name: "Qianming",
    data() {
      return {
        lineWidth: 6,
        lineColor: "#000000",
        bgColor: "",
        resultImg: "",
        isCrop: false,
      };
    },
    methods: {
      //清空画板..
      handleReset() {
        this.$refs.esign.reset();
        this.resultImg = "";
      },
      //生成签名图片..
    //   handleGenerate() {
    //       this.$refs["esign"].generate().then((res) => {
    //             this.resultImg = res; // 得到了签字生成的base64图片
    //             this.$emit("setsignin",res)
    //               // 也可以转换成在线地址
    //             //  this.dataURLtoFile(res)
    //              //转为文件流
    //             uploadPhoto('sign',this.dataURItoBlob(res)).then(res=>{
    //                 console.log(res);
    //             })
    //       }).catch((err) => {
    //         //  没有签名，点击生成图片时调用
    //         this.$message({
    //           message: " 未签名！",
    //           type: "warning",
    //         });
    //       });
    //   },
      handleGenerate() {
	  var _this = this;
	  this.$refs.esign.generate().then(res => {
		this.resultImg = res;       
        let randnum = Math.random() * 10000000000000
        randnum = Math.floor(randnum)
        let fileName = "sign" + randnum + '.png'
        let file = this.dataURLtoFile(res, fileName)

        let formData = new FormData()
        formData.append("file",file);
		    console.log(file, "file")
        // 调接口
        uploadPhoto(this.fileName,formData).then(res=>{
            console.log(res);
            if (res.success) {
                this.$emit("setsignin",res.data)
            }else {
                this.$message.error('提交失败！')
                this.$emit("setsignin",'')
            }
        })
      }).catch(err => {
        console.log(err)
        this.$message.error('请签名之后提交！')
      }) 
	},

      //将base64 上传到服务器，转换成在线地址
    //   dataURLtoFile(res) {
        // const file = this.dataURItoBlob(res)
        //   let formData = new FormData()
        //   formData.append("file",file);
          //上传图片
        //   uploadFile(formData).then(result=>{
            //   this.$emit("setsignin",result.data)
        //   })
    //   },
      dataURLtoFile(dataurl, filename) {
      var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], filename, { type: mime });
        },

      dataURItoBlob(base64Data) {
        var byteString;
        if(base64Data.split(',')[0].indexOf('base64') >= 0)
          byteString = atob(base64Data.split(',')[1]);
        else{
          byteString = unescape(base64Data.split(',')[1]);
        }
        var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
        var ia = new Uint8Array(byteString.length);
        for(var i = 0; i < byteString.length; i++) {
          ia[i] = byteString.charCodeAt(i);
        }
        var blob = new Blob([ia], {
          type: mimeString
        });
        console.log(blob);
        return blob;
      },
    },
  };
  </script>
    
  <style scoped>
  button {
    height: 40px;
  } 
   .contro-container {
    width: 600px;
    height: 50px;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-around;
    background-color: #d3d3d3;
    position: absolute;
    bottom: 0px;
  }
  .qianming-container {
    width: 600px;
    height: 350px;
    margin: 10px auto;
    position: relative;
  }
  .text {
    font-size: 14px;
  }
  .item {
    margin-bottom: 18px;
  }
  .clearfix:before,
  .clearfix:after {
    display: table;
    content: "";
  }
  .clearfix:after {
    clear: both;
  }
  .box-card {
    width: 95%;
    margin-left: 2.5%;
    margin-top: 20px;
  }
  </style>
    